package com.example.campuslink.commen.http

import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.widget.Toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream

object ImageSaver {
    suspend fun saveImageToGallery(context: Context, imageUrl: String) {
        withContext(Dispatchers.IO) {
            try {
                val response = Retrofit.instance.downloadImage(imageUrl)

                if (response.isSuccessful) {
                    response.body()?.let { body ->
                        saveImageToMediaStore(context, body.byteStream())
                        withContext(Dispatchers.Main) {
                            Toast.makeText(context, "图片保存成功", Toast.LENGTH_SHORT).show()
                        }
                    } ?: throw IOException("响应体为空")
                } else {
                    throw IOException("下载失败，状态码: ${response.code()}")
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main) {
                    Toast.makeText(context, "图片下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 保存图片到媒体库
     */
    private fun saveImageToMediaStore(context: Context, inputStream: InputStream) {
        // 生成文件名（基于时间戳）
        val fileName = "img_${System.currentTimeMillis()}.png"
        val mimeType = "image/png"

        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.MIME_TYPE, mimeType)

            // Android 10+ 使用相对路径
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
            }
        }

        val resolver = context.contentResolver
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

        uri?.let {
            resolver.openOutputStream(it).use { outputStream ->
                outputStream?.let { out ->
                    inputStream.copyTo(out)
                    out.flush()
                } ?: throw IOException("无法创建输出流")
            }
        } ?: throw IOException("无法创建媒体文件")
    }
}